package com.bang.study.day02.test;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @Auther: Bang
 * @Date: 2019/9/12 0012 15:03
 * @Description: 二叉树的中序遍历
 */
public class Solution94 {


    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        inOrder(root, list);
        return list;
    }

    private void inOrder(TreeNode root, List<Integer> list) {
        if (root==null) {
            return;
        }else{
            inOrder(root.left,list);
            list.add(root.val);
            inOrder(root.right,list);
        }
    }


    /**
     * 中序遍历 基于栈
     * @param root
     * @return
     */
    public List<Integer> inorderTraversalByStack(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if (root==null) {
            return list;
        }else{
            Stack<TreeNode> stack = new Stack<>();
            TreeNode curr = root;
            while (curr!=null||!stack.empty()) {
                while (curr!=null){
                    stack.push(curr);
                    curr = curr.left;
                }
                curr = stack.pop();
                list.add(curr.val);
                curr = curr.right;
            }

        }
        return list;
    }



    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }
}
